<template>
  <div class="createPost-container">
    <el-form
      :model="productInfo"
      :rules="rules"
      ref="ruleForm"
      label-width="100px"
      class="demo-ruleForm"
    >
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="基础信息" name="first">
          <el-form-item label="产品名称" prop="storeName">
            <el-input v-model="productInfo.storeName"></el-input>
          </el-form-item>

          <el-form-item label="产品分类" prop="cateIds">
            <el-checkbox-group v-model="productInfo.cateIds">
              <el-checkbox v-for="cate in cateList" :label="cate.key" :key="cate.key">{{cate.name}}</el-checkbox>
            </el-checkbox-group>
          </el-form-item>

          <el-form-item label="产品封面" prop="image">
            <Upload v-model="productInfo.image" />
            <span class="el-upload__tip">只能上传jpg/jpeg/png文件，建议尺寸为600px*600px</span>
          </el-form-item>

          <el-form-item label="产品视频" prop="videoLink">
            <el-upload
              class="upload-video"
              :action="uploadVideoAction"
              :on-preview="handleVideoPreview"
              :on-remove="handleVideoRemove"
              :before-remove="beforeVideoRemove"
              :multiple=false
              :limit="1"
              :on-exceed="handleVideoExceed"
              :on-success="handleVidelSuccess"
              :file-list="fileList">
              <el-button size="small" type="primary">点击上传</el-button>
              <span slot="tip" class="el-upload__tip"> 只能上传MP4文件，且不超过20M</span>
            </el-upload>
          </el-form-item>

          <el-form-item label="产品轮播图" prop="sliderImage">
            <Upload4 v-model="productInfo.sliderImage" />
            <span class="el-upload__tip">只能上传jpg/jpeg/png文件，建议尺寸为600px*600px</span>
          </el-form-item>

          <el-row :gutter="24">
            <el-col :span="12">
              <div class="grid-content bg-purple">
                <el-form-item label="售价" prop="price">
                  <el-input v-model="productInfo.price"></el-input>
                </el-form-item>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="grid-content bg-purple">
                <el-form-item label="市场价" prop="marketPrice">
                  <el-input v-model="productInfo.marketPrice"></el-input>
                </el-form-item>
              </div>
            </el-col>
          </el-row>
          <!-- 库存 -->
          <el-row :gutter="24">
            <el-col :span="12">
              <div class="grid-content bg-purple">
                <el-form-item label="库存" prop="stock">
                  <el-input v-model.number="productInfo.stock"></el-input>
                </el-form-item>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="grid-content bg-purple">
                <el-form-item label="单位" prop="unitName">
                  <el-input v-model="productInfo.unitName"></el-input>
                </el-form-item>
              </div>
            </el-col>
          </el-row>
          <!-- 排序 -->
          <el-row :gutter="24">
            <el-col :span="12">
              <div class="grid-content bg-purple">
                <el-form-item label="排序" prop="sort">
                  <el-input v-model.number="productInfo.sort"></el-input>
                </el-form-item>
              </div>
            </el-col>
          </el-row>
        </el-tab-pane>
        <el-tab-pane label="规格" name="second">
          <el-row :gutter="24">
            <el-col :span="12">
              <div class="grid-content bg-purple">
                <el-form-item label="规格" prop="specType">
                    <el-radio-group v-model="productInfo.specType">
                        <el-radio :label="0">单规格</el-radio>
                        <el-radio :label="1">多规格</el-radio>
                    </el-radio-group>
                </el-form-item>
              </div>
            </el-col>
          </el-row>
          <el-row v-if="productInfo.specType == 1">
            <el-col :span="24">
                <!-- 规格名称 -->
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="规格名称" prop="">
                            <el-input ref="specName" v-model="specName" placeholder="请输入规格名称">
                                <el-button slot="append" @click="addSpec()">添加</el-button>
                            </el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <!-- 规格内容 -->
                <el-row v-for="(item, key) in productInfo.spec.items" :key="key">
                    <el-form-item label="" prop="" style="margin-bottom:5px;">
                        <el-col :span="24">
                            <div style="color:#f60">
                                <el-tag :key="item.value" :hit="false" type="danger" closable :disable-transitions="false" @close="specClose(key)">
                                    {{ item.value }}
                                </el-tag>
                            </div>     
                            <el-tag :key="vkey" v-for="(tag, vkey) in item.detail" closable :disable-transitions="false" @close="specValueClose(key, vkey, tag)">
                                {{ tag }}
                            </el-tag> 
                            <el-input class="input-new-tag" v-model="item.temp" ref="specAttr">
                                <el-button slot="append" style="cursor:pointer;" @click="addSpecValue(key)">添加</el-button>
                            </el-input>
                        </el-col>
                    </el-form-item>
                </el-row>
                <!-- 生成按钮 -->
                <el-row style="margin-top:10px;">
                    <el-form-item>
                        <el-col :span="24">
                            <el-button type="text" @click="createSpecItems()">立即生成</el-button>
                            <span class="el-upload__tip" style="margin-left:30px;color:red;font-size:14px;">(只能上传jpg/jpeg/png文件，建议尺寸为600px*600px)</span>
                        </el-col>
                    </el-form-item>
                </el-row>
                <!-- 规格详细 -->
                <el-row v-if="productInfo.spec.attrs.length > 0">
                    <el-form-item label="" prop="" style="margin-bottom:0px;" class="spec-info">
                        <el-col class="spec-info-item-header" v-for="(item, key) in productInfo.spec.attrs[0].detail" :key="key" :span="specItemcolNumber">{{ key }}</el-col>
                        <el-col class="spec-info-item-header" :span="specItemcolNumber">图片</el-col>
                        <el-col class="spec-info-item-header" :span="specItemcolNumber">售价</el-col>
                        <el-col class="spec-info-item-header" :span="specItemcolNumber">库存</el-col>
                        <el-col class="spec-info-item-header" :span="specItemcolNumber">重量(KG)</el-col>
                        <el-col class="spec-info-item-header" :span="specItemcolNumber">产品编号</el-col>
                    </el-form-item>
                </el-row>
                <el-row v-for="(item, key) in productInfo.spec.attrs" :key="'value' + key" class="spec-info">
                    <el-form-item label="" prop="" style="margin-bottom:0px;">
                        <el-col class="spec-info-item" v-for="(info, iKey) in productInfo.spec.attrs[key].detail" :span="specItemcolNumber" :key="key + iKey">{{ info }}</el-col>
                        <el-col class="spec-info-item" :span="specItemcolNumber">
                            <Upload5 v-model="productInfo.spec.attrs[key].pic" />
                        </el-col>
                        <el-col class="spec-info-item" :span="specItemcolNumber">
                            <el-input v-model="productInfo.spec.attrs[key].price" placeholder="售价"></el-input>
                        </el-col>
                        <el-col class="spec-info-item" :span="specItemcolNumber">
                            <el-input v-model="productInfo.spec.attrs[key].stock" placeholder="库存"></el-input>
                        </el-col>
                        <el-col class="spec-info-item" :span="specItemcolNumber">
                            <el-input v-model="productInfo.spec.attrs[key].weight" placeholder="重量(KG)"></el-input>
                        </el-col>
                        <el-col class="spec-info-item" :span="specItemcolNumber">
                            <el-input v-model="productInfo.spec.attrs[key].code" placeholder="产品编号"></el-input>
                        </el-col>
                    </el-form-item>
                </el-row>
            </el-col>
          </el-row>
        </el-tab-pane>
        <el-tab-pane label="内容详细" name="three">
          <el-form-item label="产品描述" prop="storeInfo">
            <Tinymce ref="editor" v-model="productInfo.storeInfo" :height="400" />
          </el-form-item>
        </el-tab-pane>
      </el-tabs>

      <el-form-item style="margin-top:20px;">
        <el-button type="primary" @click="submitForm('ruleForm')" :loading="loading">立即保存</el-button>
        <el-button @click="resetForm('ruleForm')">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { updateProduct, getProductInfo } from "@/api/prodecuManger";
import { productCateList } from "@/api/product-cate";
import Upload from "@/components/Upload/SingleImage";
import Upload4 from "@/components/Upload/SingleImage4";
import Upload5 from "@/components/Upload/SingleImage5";
import Tinymce from "@/components/Tinymce";

export default {
  data() {
    return {
      loading: false,
      uploadVideoAction: process.env.VUE_APP_UPLOAD_BASE_URL + "api/v1/file/upload",
      uploadSliderAction: process.env.VUE_APP_UPLOAD_BASE_URL + "api/v1/file/upload",
      activeName: "first",
      cateList: [],
      fileList: [],
      sliderImages: [],
      dialogVisible: true,
      specName: '',
      specAttr: '',
      specItemcolNumber: 2,
      zum: [],
      productInfo: {
        id: 0,
        activity: "",
        barCode: "",
        cateIds: [],
        cost: 0,
        ficti: 0,
        givePoint: 0,
        image: "",
        isPostage: 0,
        is_benefit: 0,
        is_best: 0,
        is_good: 0,
        is_hot: 0,
        is_new: 0,
        is_seckill: 0,
        is_show: 0,
        is_vip: 0,
        keyword: "",
        marketPrice: 0,
        postage: 0,
        price: 0,
        recommendImage: "",
        sales: 0,
        sliderImage: "",
        sort: 100,
        stock: 0,
        storeInfo: "",
        storeName: "",
        tempId: 0,
        unitName: "",
        videoLink: "",
        vipPrice: 0, // 会员价格
        specType: 0,
        spec: {
            items: [],
            attrs: [],
        },
      },
      rules: {
        storeName: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
        ],
        cateIds: [
          { required: true, message: "请选择商品分类", trigger: "blur" },
        ],
        price: [
          {required: true,  message: "请输入价格", trigger: "blur"},
          {pattern: /\d+(\.\d{1,2})?/, message: "价格只能填写正整数和小数", trigger: "blur"}
        ],
        marketPrice: [
            {pattern: /\d+(\.\d{1,2})?/, message: "价格只能填写正整数和小数", trigger: 'blur'}
        ],
        stock: [
            {required: true, type: "number", message: "请输入库存", trigger: "blur"}
        ],
        image: [
            { required: true, message: "请上传产品图", trigger: "change" }
        ],
        unitName: [
          { required: true, message: "请填写单位", trigger: "change" },
        ],
        storeInfo: [
          { required: true, message: "请填写产品描述", trigger: "blur" },
        ],
      },
    };
  },
  components: {
    Upload,
    Upload4,
    Upload5,
    Tinymce,
  },
  created() {
    // 需要编辑的产品ID
    let id = this.$route.params && this.$route.params.id;
    // 获取产品详细
    getProductInfo({ id: id }).then((response) => {
      if (response.success == true) {
        this.productInfo.id = response.data.id;
        this.productInfo.storeName = response.data.storeName;
        this.productInfo.image = response.data.image;
        this.productInfo.price = response.data.price;
        this.productInfo.marketPrice = response.data.marketPrice;
        this.productInfo.unitName = response.data.unitName;
        this.productInfo.stock = response.data.stock;
        this.productInfo.sort = response.data.sort;
        this.productInfo.storeInfo = response.data.storeInfo;
        this.productInfo.is_show = response.data.is_show;
        this.productInfo.sliderImage = response.data.sliderImage;
        this.productInfo.specType = response.data.specType;
        this.productInfo.spec = JSON.parse(response.data.spec);

        let categoryList = response.data.productCateglories;
        for (var i in categoryList) {
          this.productInfo.cateIds.push(categoryList[i].id);
        }

        // 格式化规格数据
        if (this.productInfo.spec) {
            for (let i in this.productInfo.spec.attrs) {
                this.productInfo.spec.attrs[i].detail = JSON.parse(this.productInfo.spec.attrs[i].detail);
            }
        }

        this.productInfo.videoLink = response.data.videoLink;

        // 处理文件名称
        if (response.data.videoLink) {
          let videoNames = response.data.videoLink.split("/");
          this.fileList.push({
            name: videoNames[videoNames.length - 1],
            url: response.data.videoLink,
          });
        }
      }

      this.setSpecItemColNum();
    });

    this.getCateList();
  },
  methods: {
    getCateList() {
      // 商品分类
      productCateList({ pageType: "A" }).then((response) => {
        let data = response.data;
        for (let i in data) {
          this.cateList.push({ key: data[i].id, name: data[i].cateName });
        }
      });
    },
    submitForm(formName) {
      let that = this;
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          this.loading = true;
          try {
            for (let i in that.productInfo.spec.attrs) {
                that.productInfo.spec.attrs[i].detail = JSON.stringify(that.productInfo.spec.attrs[i].detail);
            }

            const { success, errorDetail } = await updateProduct(
              that.productInfo
            );
            if (success == true) {
              this.$notify({
                title: "成功",
                message: "产品编辑成功",
                type: "success",
                duration: 2000,
              });
              this.$router.go(-1);
            } else {
              this.$notify({
                title: "失败",
                message: errorDetail != null ? errorDetail : "产品编辑失败",
                type: "error",
                duration: 2000,
              });
            }
          } finally {
            this.loading = false;
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 创建规格详细数据
    createSpecItems() {
        console.log('attrs', this.productInfo.spec.items);
        if (this.productInfo.spec.items.length == 0) {
            this.$notify({
                title: "失败",
                message: "没有规格，添加后才能生成",
                type: "error",
                duration: 2000,
            });
            return false;
        }

        for (let i in this.productInfo.spec.items) {
            if (this.productInfo.spec.items[i].detail.length == 0) {
                this.$notify({
                    title: "失败",
                    message: "规格" + this.productInfo.spec.items[i].value + "缺少值，添加后才能生成",
                    type: "error",
                    duration: 2000,
                });

                return false;
            }
        }

        // 排列组合规格属性
        this.zum = [];
        for (let i in this.productInfo.spec.items) {
            this.setZum(i, this.productInfo.spec.items[i].detail, this.productInfo.spec.items[i].value);
        }
        this.productInfo.spec.attrs = this.zum;

        this.setSpecItemColNum();
    },
    // 组合规格详细数据
    setZum (key, rules, value) {
        // console.log(key, rules, value);
        let attrItem = {values: [], detail: {}, pic: '', price: 0, stock: 0, weight: '', code: ''};
        if (this.zum.length > 0) {
            let tempZum = [];
            for (let z in this.zum) {
                for (let i in rules) {
                    let tempAttrItem = JSON.parse(JSON.stringify(this.zum[z]));
                    tempAttrItem.values.push(rules[i]);
                    tempAttrItem.detail[value] = rules[i];
                    tempZum.push(tempAttrItem);
                }
            }

            this.zum = tempZum;
        } else { 
            for (let i in rules) {
                let tempAttrItem = JSON.parse(JSON.stringify(attrItem));
                tempAttrItem.values.push(rules[i]);
                tempAttrItem.detail[value] = rules[i];
                this.zum.push(tempAttrItem);
            }
        }
    },
    // 新增规格
    addSpec () {
        if (this.specName != '') {
            let that = this;
            this.productInfo.spec.items.push({value: that.specName, detail: [], temp: ''});
        }

        this.specName = '';
        this.setSpecItemColNum();
    },
    // 新增规格内容
    addSpecValue (index) {
        this.productInfo.spec.items[index].detail.push(this.productInfo.spec.items[index].temp);
        this.productInfo.spec.items[index].temp = '';
    },
    // 设置规格详细列长度
    setSpecItemColNum () {
        let len = 0;
        if (this.productInfo.spec.attrs.length > 0) {
            for (let i in this.productInfo.spec.attrs[0].detail) {
                len ++;
            }
        }
        this.specItemcolNumber = Math.floor(24 / (len + 5));
    },
    // 删除规格
    specClose (skey) {
        console.log('skey', skey, this.productInfo.spec.items);
        this.productInfo.spec.items.splice(skey, 1);
    },
    // 删除规格属性
    specValueClose (skey, vkey, tag) {
        this.productInfo.spec.items[skey].detail.splice(vkey, 1);
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    handleClick(tab, event) {
      console.log(tab, event);
    },    
    // 视频
    handleVideoRemove(file, fileList) {
      this.productInfo.videoLink = "";
      console.log("video", file, fileList);
    },
    handleVideoPreview(file) {
      console.log("video", file);
      window.open(file.url);
    },
    handleVideoExceed(files, fileList) {
      // this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    handleVidelSuccess(response, file, fileList) {
      if (response.success == true) {
        this.productInfo.videoLink = response.data.path;
      }
    },
    beforeVideoRemove(file, fileList) {
      // return this.$confirm(`确定移除 ${ file.name }？`);
    },
    // 轮播
    handleSliderSuccess(res, file) {
      if (res.success === true) {
        this.sliderImages.push(res.data.path);
      }
      // this.imageUrl = URL.createObjectURL(file.raw);
    },
    beforeSliderUpload(file) {
      // const isJPG = file.type === 'image/jpeg';
      // const isLt2M = file.size / 1024 / 1024 < 2;
      // if (!isJPG) {
      //   this.$message.error('上传头像图片只能是 JPG 格式!');
      // }
      // if (!isLt2M) {
      //   this.$message.error('上传头像图片大小不能超过 2MB!');
      // }
      // return isJPG && isLt2M;
    },
  },
};
</script>

<style lang="scss" scoped>
@import "~@/styles/mixin.scss";
.spec-info:last-child .spec-info-item {
    border-bottom: 1px solid #eee;
}
.spec-info .spec-info-item-header{
    font-weight: bold;
}
.spec-info .spec-info-item,.spec-info-item-header {
    padding: 5px;
    border-top: 1px solid #eee;
    border-left: 1px solid #eee;
    text-align: center;
}
.spec-info .spec-info-item:last-child,.spec-info-item-header:last-child {
    border-right: 1px solid #eee;
}
.el-tag + .el-tag {
    margin-left: 10px;
}
.button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
}
.input-new-tag {
    width: 180px;
    margin-left: 10px;
    vertical-align: bottom;
}

.createPost-container {
  position: relative;
  margin-top: 20px;
  padding: 10px;
  box-sizing: border-box;
  .createPost-main-container {
    padding: 40px 45px 20px 50px;

    .postInfo-container {
      position: relative;
      @include clearfix;
      margin-bottom: 10px;

      .postInfo-container-item {
        float: left;
      }
    }
  }

  .word-counter {
    width: 40px;
    position: absolute;
    right: 10px;
    top: 0px;
  }
}

.article-textarea ::v-deep {
  textarea {
    padding-right: 40px;
    resize: none;
    border: none;
    border-radius: 0px;
    border-bottom: 1px solid #bfcbd9;
  }
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
